from common.config import torqueConfig as Config

import numpy as np
import pandas as pd

class CleanDecorator:

    # 在装饰器函数里传入参数
    def drop_duplicates(fun1):
        def wrapper(x):
            #x = x.drop_duplicates()  # 删除重复行
            x = x.fillna(value=0)  # 对缺失值进行填充 ,用实数0填充na
            print('After drop_duplicates: ', len(x))
            return fun1(x)
        return wrapper

    def drop_bigorsmall(fun1): #过滤不合法数据
        def wrapper(x):
            x = x[(x[Config.WindSpeed] >= Config.windSpeedFilter_min) & (x[Config.WindSpeed] <= Config.windSpeedFilter_max)
                  & (x[Config.ActPower] >= Config.powerFilter_min) & (x[Config.ActPower] <= Config.powerFilter_max)
                  & (x[Config.RotateSpeed] >= Config.rotateSpeedFilter_min) & (x[Config.RotateSpeed] <= Config.rotateSpeedFilter_max)]
            print('After drop_bigorsmall: ', len(x))
            return fun1(x)
        return wrapper

    def drop_discretePoint(fun1): # 过滤离散点
        def wrapper(x):
            #将WindSpeed 轴划分小段，每段长度 Config.scale_WindSpeed
            min_windSpeed = min(x[Config.WindSpeed])
            max_windSpeed = max(x[Config.WindSpeed])
            x_result = pd.DataFrame()
            for speed in np.arange(min_windSpeed, max_windSpeed, Config.scale_WindSpeed):
                points_slice = x[(x[Config.WindSpeed]>=speed) & (x[Config.WindSpeed]<speed+Config.scale_WindSpeed)]  # 统计切 speed 轴 切片中的点
                mean = np.mean(points_slice[Config.ActPower])
                sigma = np.std(points_slice[Config.ActPower])  # 计算均值和标准差

                data2 = points_slice[np.fabs(points_slice[Config.ActPower]-mean)<3*sigma] # 保留偏离均值 < 3*sigma 的点
                x_result = pd.concat([x_result, data2])

            print('After drop_discretePoint: ', len(x_result))
            return fun1(x_result)
        return wrapper

    def drop_discretePoint_2(fun1): # 过滤离散点,垂直speed轴切片，进行一次函数拟合，去除距离直线较远的点
        def wrapper(x):
            #将WindSpeed 轴划分小段，每段长度 Config.scale_WindSpeed
            min_windSpeed = min(x[Config.WindSpeed])
            max_windSpeed = max(x[Config.WindSpeed])
            x_result = pd.DataFrame()
            for speed in np.arange(min_windSpeed, max_windSpeed, Config.scale_WindSpeed):
                points_slice = x[(x[Config.WindSpeed]>=speed) & (x[Config.WindSpeed]<speed+Config.scale_WindSpeed)]  # 统计切 speed 轴 切片中的点

                f1 = np.polyfit(points_slice[Config.RotateSpeed], points_slice[Config.ActPower], 2)  # 返回多项式系数
                func = np.poly1d(f1)  # 返回多项式表达式（多项式函数）
                data2 = points_slice[np.fabs(func(points_slice[Config.RotateSpeed]) - points_slice[Config.ActPower])<150]  # 保留点距离拟合曲线距离<50的点
                x_result = x_result.append(data2)

            print('After drop_discretePoint: ', len(x_result))
            return fun1(x_result)
        return wrapper






